package com.ctaa;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.common.api.RouterPath;
import com.common.utils.Constants;
import com.common.utils.ConstantsUrl;
import com.common.utils.MethodUtils;
import com.ctaa.databinding.ActivityMainBinding;
import com.ctaa.login.LoginActivity;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.patch.AppUpdate;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class MainActivity extends AppCompatActivity {


    private ActivityMainBinding mainBinding;
    private BroadcastReceiver receiver;//注册内部广播接收点击信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mainBinding.getRoot());

        //检查更新
        updateVsersion();

        if (Constants.userInfo == null) {
            //登陆失效，请重新登陆
            Toast.makeText(this, "登陆失效，正在前往登陆页面", Toast.LENGTH_SHORT).show();
            startLoginPage();
            return;
        }


        mainBinding.bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.analysis:
                        replaceFragment((Fragment) ARouter.getInstance().build(RouterPath.ANALYSIS_MAIN).navigation());
                        return true;
                    case R.id.detail:
                        replaceFragment((Fragment) ARouter.getInstance().build(RouterPath.DETAIL_MAIN).navigation());
                        return true;
                    case R.id.bkkp:
                        replaceFragment((Fragment) ARouter.getInstance().build(RouterPath.BKKP_MAIN).navigation());
                        return true;
                    case R.id.mine:
                        replaceFragment((Fragment) ARouter.getInstance().build(RouterPath.MINE_MAIN).navigation());
                        return true;
                }
                return false;
            }
        });
        //组件之间跳转和访问父组件操作方法
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String itemId = intent.getStringExtra("selectItemId");
                if ("analysis".equalsIgnoreCase(itemId)) {
                    mainBinding.bottomNavigation.setSelectedItemId(R.id.analysis);
                } else if ("detail".equalsIgnoreCase(itemId)) {
                    mainBinding.bottomNavigation.setSelectedItemId(R.id.detail);
                } else if ("bkkp".equalsIgnoreCase(itemId)) {
                    mainBinding.bottomNavigation.setSelectedItemId(R.id.bkkp);
                } else if ("mine".equalsIgnoreCase(itemId)) {
                    mainBinding.bottomNavigation.setSelectedItemId(R.id.mine);
                } else if ("logout".equalsIgnoreCase(itemId)) {
                    //退出登录
                    startLoginPage();
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.pdd.SELECT_NAVIGATION_ITEM");
        registerReceiver(receiver, filter);

        // 默认显示第一个 记账Fragment
        mainBinding.bottomNavigation.setSelectedItemId(R.id.bkkp);
    }

    private void updateVsersion() {
        AppUpdate.appUpdate(1, this, "com.ctaa",MethodUtils.getFilesDir(), ConstantsUrl.versionUrl);
    }

    private void replaceFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    private void startLoginPage() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("提示")
                    .setContentText("是否退出系统？")
                    .setConfirmText("确定")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            System.exit(0);
                        }
                    })
                    .setCancelText("取消")
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    })
                    .show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}